#pragma once
#define FIFO_FILE "fifo"
#include<cstring>
#include<iostream>
#include<sys/types.h>
#include<sys/stat.h>
#include<string>
#include<fcntl.h>
#include<unistd.h>

class NamedFifo
{
public:
    NamedFifo(const std::string& path,const std::string& name)
    :_path(path) , _name(name)
    {
        //创建管道
        umask(0);
        _fifoname = _path + "/" + _name;
        int n = mkfifo(_fifoname.c_str(),0666);
        if(n < 0)
        {
            std::cerr << "mkdir fifo error" << std::endl;
            exit(1);
        }
        std::cerr << "mkdir fifo success" << std::endl;
    }
    ~NamedFifo()
    {
        //删除管道
        int n = unlink(_fifoname.c_str());
        if(n == 0)
        {
            std::cout << "unlink fifo success" << std::endl;
        }
        else
        {
            std::cerr << "unlink fifo error" << std::endl;
        }
    }
private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
};

class FileOper
{
public:
    FileOper(const std::string& path,const std::string& name)
    :_path(path),_name(name)
    {
        _fifoname = _path + "/" + _name;
    }
    void OpenForRade()
    {
        //打开文件
        _fd = open(_fifoname.c_str(),O_RDONLY);
        if(_fd < 0)
        {
            std::cerr << "open fifo error" << std::endl;
            exit(1);
        }
        std::cout << "open fifo success" << std::endl;
    }
    void OpenForWrite()
    {
        _fd = open(_fifoname.c_str(),O_WRONLY);
        if(_fd < 0)
        {
            std::cerr << "open fifo error" << std::endl;
            exit(1);
        }
        std::cout << "open fifo success" << std::endl;
    }

    bool Read()
    {

        char c = 0;
        int number = read(_fd,&c,1);
        printf("唤醒:%d\n",c);
        if(number == 0)
        {
            return false;
        }
        return true;
    }
    void Write()
    {

        char c = 1;
        int number = write(_fd,&c,1);
        printf("尝试唤醒:%d\n",c);
        (void) number;
    }
    void Close()
    {
        close(_fd);
    }
    ~FileOper()
    {

    }
private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
    ssize_t _fd;
};